#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Thread.hpp"

using namespace std;

void Usage(string proc)
{
    cout << "Usage:\n\t" << "please input: " << proc << " serverip serverport" << endl;
}
// 初始化用户，返回相应的套接字描述符
int InitClient(string& serverip, uint16_t serverport, struct sockaddr_in* server)
{
    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        cerr << "socket error" << endl;
        exit(1);
    }
    // 构建目标主机的socket信息
    memset(server, 0, sizeof(struct sockaddr_in));
    server->sin_family = AF_INET;
    server->sin_port = htons(serverport);
    server->sin_addr.s_addr = inet_addr(serverip.c_str());
    return sockfd;
}
// 向服务器中发送数据
void sendmessage(int sockfd, struct sockaddr_in& serveraddr, string name)
{
    string message;
    while (true)
    {
        printf("%s | Enter# ", name.c_str());
        fflush(stdout);
        getline(cin, message);
        sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&serveraddr, sizeof(serveraddr));
    }
}

int main(int argc, char *argv[])
{
    // 处理输入连接服务器的IP地址和端口号
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);
    struct sockaddr_in serveraddr;
    int sockfd = InitClient(serverip, serverport, &serveraddr);

    func_t s = bind(&sendmessage, sockfd, serveraddr, placeholders::_1);

    Thread Sender(s, "sender");
    Sender.Start();
    Sender.Detach();
    while (true)
    {   }
    return 0;
}